package com.ly.springcloud.controller;

import com.ly.springcloud.entities.CommonResult;
import com.ly.springcloud.entities.Payment;
import com.ly.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author: liangyuan
 * @Date: 2020/10/27 11:34:11
 * @Description: 支付模块控制层
 */
@RestController
@Slf4j
public class PaymentController {

    @Resource
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    @Resource
    private DiscoveryClient discoveryClient;

    @PostMapping(value = "/payment/savePayment")
    public CommonResult savePayment(@RequestBody Payment payment){
        int result = paymentService.savePayment(payment);
        log.info("savePayment******执行结果："+result);
        if (result > 0) {
            return new CommonResult(200, "插入数据成功！端口为："+serverPort, result);
        } else {
            return new CommonResult(444, "插入数据失败！端口为："+serverPort, null);
        }
    }

    @GetMapping(value = "/payment/getPaymentById/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id){
        Payment result = paymentService.getPaymentById(id);
        log.info("getPaymentById******执行结果："+result);
        if (result!=null) {
            return new CommonResult(200, "查询成功！端口为："+serverPort, result);
        } else {
            return new CommonResult(444, "无此记录！端口为："+serverPort, null);
        }
    }

    @GetMapping(value = "/payment/discoveryclient")
    public Object discoveryclient(){
        //获取微服务名称
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("********getServies():"+service);
        }
        //获取微服务所有信息
        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-payment-service");
        for (ServiceInstance instance : instances) {
           log.info(instance.getInstanceId()+"\t"+instance.getHost()+"\t"+instance.getServiceId()+"\t"+instance.getPort()+"\t"+instance.getUri());
        }
        return this.discoveryClient;
    }

}
